#!/usr/bin/python
# coding=utf-8

# import requests
# pip install selenium==4.1.0
from selenium import webdriver
import os
import requests

class ChromeWebDriver(webdriver.Chrome):
    def __init__(self):
        self.options = webdriver.ChromeOptions()

        # 禁用自动化栏
        self.options.add_experimental_option('excludeSwitches', ['enable-automation'])
        self.options.add_experimental_option('useAutomationExtension', False)
        self.options.add_argument('--disable-blink-features=AutomationControlled')
        self.options.add_argument('--headless')
        self.options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.57')

        # self.service = Service('chromedriver.exe')
        # self.driver = webdriver.Chrome(service=self.service, options=self.options)
        if __name__ == '__main__':
            executable_path = 'chromedriver.exe'
        else:
            executable_path = './chrome/chromedriver.exe'
        super().__init__(executable_path=executable_path, options=self.options)

        # 修改 webdriver 值
        # 读取文件
        if __name__ == '__main__':
            js_path = os.path.join(os.getcwd(), '../stealth_min/stealth.min.js')
        else:
            js_path = os.path.join(os.getcwd(), './stealth_min/stealth.min.js')
        if os.path.exists(js_path):
            with open(js_path, 'r') as f:
                js = f.read()

            # 调用函数在页面加载前执行脚本
            self.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js})
        else:
            self.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
                "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """})

    def get_url(self, url: str, wait: int = 10):
        self.get(url)
        self.implicitly_wait(10)
